#! /bin/bash

# ---------------------------------------------------------------------------------------
# @title   进入 docker 运行中的容器
# @author  LuYao
# @date    2023/06/18
# @encode  UTF-8
# @description
#   1 通过 nsenter 命令在 shell 进入运行时容器
#   2 全局使用：
#               cp dock-in.sh /usr/local/sbin/docker-in
#               docker-in mysql
#
# 参考：
#
# ---------------------------------------------------------------------------------------

# get container id
container_id=`docker ps | grep -v CONTAINER | grep $1 | awk -F ' ' '{print $1}'`
if [[ -z $container_id ]]; then
        printf "\033[;31m Container [$1] not exist.\033[0m\n"
        exit
fi

printf "Container  ID: \033[;32m$container_id\033[0m\n"

# get container pid
container_pid=`docker inspect --format "{{.State.Pid}}" $container_id`
if [[ -z $container_pid || $container_pid == 0 ]]; then
        printf "\033[;31mContainer [$1] pid not exist.\033[0m\n"
        exit
fi

printf "Container PID: \033[;32m$container_pid\033[0m\n"

# enter container
nsenter --target $container_pid --mount --uts --ipc --net --pid /bin/bash